package it.polimi.swimv2.session;

import it.polimi.swimv2.entities.Feedback;
import it.polimi.swimv2.entities.User;
import it.polimi.swimv2.exception.UserNotFoundException;
import it.polimi.swimv2.remote.UserProfileManagerRemote;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class UserProfileManager
 */
@Stateless
public class UserProfileManager implements UserProfileManagerRemote {

	@PersistenceContext(unitName = "swimv2")
	private EntityManager em;

	@EJB FriendsManagerLocal friendsManager;
	@EJB FriendshipRequestManagerLocal friendshipRequestManager;
	/**
	 * Default constructor.
	 */
	public UserProfileManager() {
		super();
	}

	@Override
	public User getUserDetail(String username) throws UserNotFoundException {
		User u = em.find(User.class, username);
		if(u!=null){
			return u;
		}else{
			throw new UserNotFoundException();
		}
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Feedback> getFeedbackOf(String username) {
		Query q = em
				.createQuery("FROM Feedback F WHERE F.receiver.username= :user ");
		q.setParameter("user", username);
		List<Feedback> resultList = new ArrayList<Feedback>(q.getResultList());
		return resultList;
	}

	@Override
	public boolean areFriend(String username1, String username2) {
		if (username1 == null || username2 == null) {
			return false;
		}
		User u1 = em.find(User.class, username1);
		User u2 = em.find(User.class, username2);
		
		return friendsManager.areFriends(u1, u2);
	}

	@Override
	public boolean existFriendshipRequest(String username1, String username2) {
		if (username1 == null || username2 == null) {
			return false;
		}
		User u1 = em.find(User.class, username1);
		User u2 = em.find(User.class, username2);
		return friendshipRequestManager.existFriendshipRequest(u1, u2);
	}

}
